package net.sk.rm;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

import net.sk.mina.imagine.codec.ImageResponseDecoder;
import net.sk.pt.State;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

public class rmDecoder extends CumulativeProtocolDecoder {
    private static final String DECODER_STATE_KEY = ImageResponseDecoder.class.getName() + ".STATE";
	static int LEN_DEFAULT = 4;
	 
	 
    private static class DecoderState {
        int buflen = LEN_DEFAULT;
        boolean bfh = true;
        State s;
        byte[] f;
    }
	@Override
	protected boolean doDecode(IoSession session, IoBuffer in,
			ProtocolDecoderOutput out) throws Exception {
		// TODO Auto-generated method stub
		DecoderState ds = (DecoderState) session.getAttribute(DECODER_STATE_KEY);
        if (ds == null) {
        	ds = new DecoderState();
            session.setAttribute(DECODER_STATE_KEY, ds);
        }
        if (in.remaining() >= ds.buflen) {
        	if(ds.bfh){
        		ds.bfh=false;
        		ds.buflen=in.getInt();
        		return false;
        	}else{
                byte[] b_in = new byte[ds.buflen];
                in.get(b_in);
                Object rmData = decode(b_in);
                out.write(rmData);
                return true;
        	}            
        } else {
            return false;
        }
	}
	static public Object decode(byte[] b_in) throws IOException, ClassNotFoundException{
		ByteArrayInputStream bi = new ByteArrayInputStream(b_in);
		ObjectInputStream oi = new ObjectInputStream(bi);   
	    Object obj = oi.readObject();   
	    bi.close();   
	    oi.close();
	    return obj;
	}        
	 
	 
}
